package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.IotClientConfig;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDataVo;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备类型Service业务层处理
 * 
 * @author 大黑牛
 * @date 2025-10-17
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper,Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IotClientConfig iotClientConfig;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IoTDAClient client;

    /**
     * 查询设备类型列表
     * 
     * @param device 设备类型
     * @return 设备类型
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }


    /**
     *  物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);

        ListProductsResponse listProductsResponse = iotClientConfig.huaWeiIotInstance().listProducts(request);

        if (listProductsResponse.getHttpStatusCode() !=200){
            throw new BaseException("获取产品设备异常!!!");
        }

        List<ProductSummary> products = listProductsResponse.getProducts();


        stringRedisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).set(JSONUtil.toJsonStr(products));
    }

    @Override
    public List<ProductVo> allProduct() {
        String s = stringRedisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).get();
        if (s == null){
            throw new BaseException("获取列表异常");
        }
        List<ProductVo> productVos = JSONUtil.toList(s, ProductVo.class);
        return productVos;
    }

    @Override
    public void register(DeviceDto dto) {
        //查询设备名称是否重复

        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getDeviceName, dto.getDeviceName());
        if (this.count(wrapper) > 0 ) {
            throw new BaseException("设备名称重复");
        }
        wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getNodeId, dto.getNodeId());
        if (this.count(wrapper) > 0 ) {
            throw new BaseException("设备标识重复");
        }
        wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getRemark, dto.getRemark());
        wrapper.eq(Device::getProductKey, dto.getProductKey());
        if (this.count(wrapper) > 0 ) {
            throw new BaseException("同一个位置重复绑定了相同的产品重复");
        }
        //查询设备标识是否重复
        //查询同一个位置是否绑定了相同的产品
        //调用IOT接口注册设备（注意设备deviceSecret需要自己生成）
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        //body.setDeviceId();
        body.setNodeId(dto.getNodeId());
        body.setDeviceName(dto.getDeviceName());
        body.setProductId(dto.getProductKey());
        //秘钥  不要类型  要32位
        AuthInfo authInfo = new AuthInfo();
        //要随机的32位
        String secret = RandomUtil.randomString(32);
        authInfo.setSecret(secret);
        body.setAuthInfo(authInfo);
        body.setDescription(dto.getDeviceDescription());
        //新增用body，把前端的dto数据都给request.setBody(body);
        request.setBody(body);
        //已经新增设备

        AddDeviceResponse response = iotClientConfig.huaWeiIotInstance().addDevice(request);
        //判断201是否新增成功
        if (response.getHttpStatusCode() !=201){
            throw new BaseException("该IOT设备新增异常！！！");
        }
        String deviceId = response.getDeviceId();


        //本地存储设备
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setIotId(deviceId);
        device.setSecret(secret);
        this.save(device);
    }

    @Override
    public DeviceDetailVo getIotId(String iotId) {
        // IOT查询
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response.getHttpStatusCode() !=200){
            throw new BaseException("获取异常");
        }


        // 本地查询
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getIotId, iotId);
        Device device = this.getOne(wrapper);
        if (device == null) {
            throw new BaseException("获取异常");
        }

        DeviceDetailVo detailVo = BeanUtil.toBean(device, DeviceDetailVo.class);

        //设备状态
        detailVo.setDeviceStatus(response.getStatus());


        String activeTimeStr = response.getActiveTime();
        // 2025-06-01T08:24:24.349Z
        // 把字符串转成LocalDateTime
        LocalDateTime parse = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
        // DateTimeZoneConverter是今天资料中提供的一个工具类
        LocalDateTime activeTime = DateTimeZoneConverter.utcToShanghai(parse);
        // 把字符串转成LocalDateTime
        detailVo.setActiveTime(activeTime);


        // DateTimeZoneConverter是今天资料中提供的一个工具类
        return detailVo;
    }

    @Override
    public List<DeviceDataVo> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);


        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() !=200){
            throw new BaseException("我报错了，没有设备影子,故障");
        }

        List<DeviceShadowData> shadowDataList = response.getShadow();
        DeviceShadowData deviceShadowData = shadowDataList.get(0);
        DeviceShadowProperties reported = deviceShadowData.getReported();

        String eventTime = reported.getEventTime();
        // 2025-06-01T08:24:24.349Z
        // 把字符串转成LocalDateTime
        LocalDateTime parse = LocalDateTimeUtil.parse(eventTime,"yyyyMMdd'T'HHmmss'Z'");
        // DateTimeZoneConverter是今天资料中提供的一个工具类
        LocalDateTime toShanghai = DateTimeZoneConverter.utcToShanghai(parse);
        // 把字符串转成LocalDateTime

        //他是一个大集合好多属性
        List<DeviceDataVo> list = new ArrayList<>();

        LinkedHashMap<String,Object> properties = (LinkedHashMap<String, Object>) reported.getProperties();
        /*for (String s : properties.keySet()) {  iter

        }*/
        Set<String> keySet = properties.keySet();
        for (String key : keySet) {
            DeviceDataVo deviceDataVo = new DeviceDataVo();
            deviceDataVo.setFunctionId(key);
            deviceDataVo.setEventTime(toShanghai);
            deviceDataVo.setValue(properties.get(key));

            list.add(deviceDataVo);
        }


        return list;
    }


    @Override
    public void updateDevice(DeviceDto dto) {
        //iot
        UpdateDeviceRequest request = new UpdateDeviceRequest();

        request.setDeviceId(dto.iotId);

        UpdateDevice body = new UpdateDevice();

        body.setDeviceName(dto.getDeviceName());
        body.setDescription(dto.getDeviceDescription());
        AuthInfoWithoutSecret authInfobody = new AuthInfoWithoutSecret();
        authInfobody.withSecureAccess(true);
        body.setAuthInfo(authInfobody);

        body.withExtensionInfo(dto.getRemark());
        body.withDescription("大黑牛watermeter device");

        request.setBody(body);

        UpdateDeviceResponse response = client.updateDevice(request);
        if (response.getHttpStatusCode() !=200){
            throw new BaseException("获取异常");
        }
        System.out.println(response.toString());
        String deviceId = response.getDeviceId();
        //本地
        LambdaUpdateWrapper<Device> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Device::getIotId, deviceId);
        wrapper.set(Device::getDeviceName, dto.getDeviceName());
        wrapper.set(Device::getRemark, dto.getRemark());
        wrapper.set(Device::getDeviceDescription, dto.getDeviceDescription());
        wrapper.set(Device::getLocationType, dto.getBindingLocation());
        //绑定位置
        wrapper.set(Device::getLocationType, dto.getLocationType());
        //位置类型
        this.update(wrapper);
    }

    @Override
    public void deleteDevice(String iotId) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        DeleteDeviceResponse response = client.deleteDevice(request);
        if (response.getHttpStatusCode() !=204){
            throw new BaseException("数据异常！！！没有删掉");
        }

        LambdaUpdateWrapper<Device> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Device::getIotId, iotId);
        this.remove(wrapper);
    }

    @Override
    public AjaxResult queryProduct(String productKey) {
        if (StringUtils.isEmpty(productKey)) {
            throw new BaseException("产品数据异常");
        }

        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if (response.getHttpStatusCode() !=200){
            throw new BaseException("产品异常");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (CollUtil.isEmpty(serviceCapabilities)) {
            return AjaxResult.success(Collections.emptyList());
        }

        return AjaxResult.success(serviceCapabilities);
    }

}
